package org.algorithm.wE1.链表;

import org.algorithm.common.ListNode;

/*****
 *
 *      周末的题：  周一要看，  没写的， 嘿嘿。。。   你们懂的
 *   参考uri: https://leetcode-cn.com/problems/reverse-ListNodes-in-k-group/
 *
 */
public class K个一组反转链表 {

    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10,11};
        ListNode node = ListNode.build(arr);
        ListNode.print(node);
        System.out.println();
        ListNode.print(reverseKGroup(node,2));
    }

    private static ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next == null || k== 0 ){
            return head;
        }
        ListNode dummyNode  = new ListNode(-1);
        dummyNode.next = head;
        ListNode pre = dummyNode;
        ListNode end = dummyNode;
        while (end.next!=null){
            //扫描待翻转范围
            for (int i = 0; i <k && end !=null ; i++) {
                end = end.next;
            }
            if(end == null){
                break;
            }
            ListNode start = pre.next;
            ListNode next = end.next;
            //断开链表
            end.next = null;
            //翻转
            pre.next = reveres(pre);
            //连接链表
            start.next = next;
            //更换指针
            pre = start;
            end = start;
        }
        return dummyNode.next;
    }

    /**
     * 反轉
     * @param head1
     * @return
     */
    private static ListNode reveres(ListNode head1) {
        if(head1 == null || head1.next == null){
            return head1;
        }
        ListNode pre1 = null;

        while (head1!=null){
            ListNode temp = head1.next;
            head1.next = pre1;
            pre1 = head1;
            head1 = temp;
        }
        return pre1;
    }
}
